package tw.miku.protocol.cus;

import java.nio.charset.CharacterCodingException;

import org.apache.mina.core.session.IoSession;

import tw.miku.GameMain;
import tw.miku.ServerParam;
import tw.miku.model.Group;
import tw.miku.model.User;
import tw.miku.protocol.codec.AbstractRequestMessagePack;
import tw.miku.protocol.codec.login.LoginRequestPack;
import tw.miku.protocol.codec.login.LoginResponsePack;
import tw.miku.protocol.codec.user.UserOnlineResponsePack;

public class LoginHandler implements IMessageHandler
{
	// public static final String NAME = "login";

	public LoginHandler()
	{

	}

	@Override
	public void handleData(AbstractRequestMessagePack message, IoSession session)
			throws CharacterCodingException
	{
		LoginRequestPack pack = (LoginRequestPack) message;
		if (null != pack)
		{
			String name = pack.username;
			Group group = GameMain.getGroup();

			LoginResponsePack rPack = new LoginResponsePack();

			if (group.containUser(name))
			{
				rPack.result = 1;
				session.write(rPack.encode());
				return;
			}

			User user = new User();
			user.setId(session.getId());
			user.setName(name);
			// user.set
			user.setSession(session);
			user.setStatus(User.STATUS_LOBBY);

			rPack.result = 0;
			rPack.marjorVersion = ServerParam.MARJOR_VERSION;
			rPack.minorVersion = ServerParam.MINOR_VERSION;
			rPack.name = name;
			rPack.id = (int) session.getId();
			rPack.rooms = group.getRooms();
			rPack.users = group.getUsers();
			session.write(rPack.encode());
			group.addUser(user);

			UserOnlineResponsePack onlinePack = new UserOnlineResponsePack();
			onlinePack.user = user;
			group.sendToAllUser(onlinePack.encode(), User.STATUS_LOBBY);

		}
	}
}
